import { Exclude } from 'class-transformer';
import {
  Column,
  CreateDateColumn,
  DeleteDateColumn,
  Entity,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';

export function formatDate(date?: Date): string | null {
  if (!date) {
    return null;
  }
  if (typeof date === 'string') {
    return date;
  }

  // 获取年月日时分秒
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以加1，并补零
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  // 使用模板字符串拼接成目标格式
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

@Entity()
export class Demo {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({
    length: 50,
    collation: 'utf8mb4_bin',
    type: 'varchar',
    comment: '名称',
  })
  name: string;

  @Column({
    length: 36,
    type: 'varchar',
    comment: '分类id',
  })
  categoryId: string;

  @Exclude()
  @Column({
    length: 36,
    type: 'varchar',
    comment: '所属用户id',
  })
  owner: string;

  @CreateDateColumn({
    transformer: {
      to: (value) => value,
      from: (value) => {
        console.log('createAt:', value);
        return formatDate(value);
      },
    },
    nullable: false,
    comment: '创建时间',
    length: 0,
    update: false,
  })
  createAt: string;

  @UpdateDateColumn({
    transformer: {
      to: (value) => value,
      from: (value) => {
        console.log('updateAt:', value);
        return formatDate(value);
      },
    },
    nullable: false,
    comment: '最后修改时间',
  })
  updateAt: string;

  @DeleteDateColumn({
    transformer: {
      to: (value) => value,
      from: (value: Date) => {
        console.log('deleteAt:', value);
        return formatDate(value);
      },
    },
    nullable: true,
    comment: '删除时间',
  })
  deleteAt: string | null;
}
